package com.hjy.order.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Configuration
public class RabbitConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @PostConstruct
    public void setRabbitTemplate() {
        /**
         * CorrelationData correlationData  – 回调的相关数据。
         * boolean ack – ack 为 true，nack 为 false
         * String Cause -- 可选原因，用于 nack，如果可用，否则为 null
         */
        // 当消息进入 rabbitMQ ,就会触发这个回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("correlationData = " + correlationData);
            System.out.println("ack = " + ack);
            System.out.println("cause = " + cause);
        });

        /**
         * Message message : 返回的消息, 可以获取消息体
         * int replyCode, : 返回的状态码
         * String replyText : 服务器返回的文本
         * String exchange : 交换机名称
         * String routingKey : 本次消息的路由 key
         */
        // 当消息没有投递到队列, 就会触发这个回调
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("message = " + message);
            System.out.println("replyCode = " + replyCode);
            System.out.println("replyText = " + replyText);
            System.out.println("exchange = " + exchange);
            System.out.println("routingKey = " + routingKey);
        });
    }
}
